package com.cmwa.solution.base.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;

import com.cmwa.solution.base.service.BatchOperService;

@SuppressWarnings({ "unchecked", "rawtypes" })
public class BatchOperServiceImpl implements BatchOperService{

	@Resource(name="sqlSessionTemplate")
	SqlSessionTemplate sqlSessionTemplate;

	/**
	 * 分批插入数据库
	 * @param methodPath  插入方法路径（全路径）
	 * @param dataList    需要插入的全量list集合
	 * @param insetQty    一次性插入的次数
	 * @throws Exception 
	 */
	@Override
	public void batchOperateData(String methodPath, List dataList, int insetQty) throws Exception {
		if (CollectionUtils.isEmpty(dataList) || StringUtils.isBlank(methodPath)) {
			return;
		}
		//默认每五十条连库插入一次
		if (insetQty == 0) {
			insetQty = 50;
		}
		SqlSession sqlSession=sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH, false);			
		try {
			List<Object> insertList = new ArrayList<Object>();
			Object newVo =  null;
			Iterator<Object> it = dataList.iterator();
			int i = 0;
			while(it.hasNext()){
				newVo = it.next();
				insertList.add(newVo);
			    i++;
			    if(i == insetQty){
			    	sqlSession.insert(methodPath, insertList);
					sqlSession.commit();
					insertList.clear();
					i = 0;
			    }
			}
			//如果有剩余的数据，则在这里插入
			if(CollectionUtils.isNotEmpty(insertList)){
				sqlSession.insert(methodPath, insertList);
			    sqlSession.commit();
			
			}
		} catch (Exception e) {
			e.printStackTrace();
			sqlSession.rollback();
			 throw e;
		}finally{
			sqlSession.close();
		}
	}
}
